package com.nbg.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.SocketException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.telnet.TelnetClient;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import com.nbg.monitor.NotificationService;

/**
 * 重启路由器
 * 
 * @author nbg
 * 
 */
public class RebootService extends NotificationService {
	private Handler handler;
	private Runnable r = new Runnable() {
		
		private void ddns(){
			try {
				HttpGet get = new HttpGet(
						"http://nic.changeip.com/nic/update?system=dyndns&hostname=nibaogang.ddns.info");
				get.addHeader("Authorization",
						"Basic bmliYW9nYW5nQDE2My5jb206ZHVndWRhbw==");
				HttpResponse response = new DefaultHttpClient().execute(get);
				
				int code = response.getStatusLine().getStatusCode();
				String res=EntityUtils.toString(response.getEntity());
				Log.i("reboot", "ddns code:" + code+"  "+res);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void run() {
			try {
				SharedPreferences preferences = getMonitorConfig();
				long reboot_time = (System.currentTimeMillis() - preferences
						.getLong("last_reboot_time", 0)) / 60000;
				Log.i("reboot", "last_reboot_time:" + reboot_time);
				if (reboot_time >= 30) {
					rebootHuawei(preferences);
				} else if (reboot_time > 1) {
					boolean network_test = preferences.getBoolean(
							"network_test", false);
					Log.i("reboot", "test baidu url network_test:"+network_test);
					if (!network_test) {
						try {
							HttpClient httpClient=new DefaultHttpClient();
							HttpResponse response = httpClient 
									.execute(new HttpGet(
											"http://www.baidu.com"));
							int code = response.getStatusLine().getStatusCode();
							Log.i("reboot", "code:" + code);
							if (code == 200) {
								Editor editor = preferences.edit();
								editor.putBoolean("network_test", true);
								editor.commit();
								ddns();
							} else {
								rebootHuawei(preferences);
							}
						} catch (Exception e) {
							e.printStackTrace();
							rebootHuawei(preferences);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	public void onCreate() {
		super.onCreate();
		HandlerThread handlerThread = new HandlerThread("reboot");
		handlerThread.start();
		handler = new Handler(handlerThread.getLooper());
	}

	public RebootService() {
		super(6, CONFIG_REBOOT);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		handler.removeCallbacks(r);
		handler.post(r);
		Log.i("reboot", "check reboot");
		return super.onStartCommand(intent, flags, startId);
	}

	public static void rebootHuawei(SharedPreferences preferences) {
		TelnetClient tc = new TelnetClient();
		try {
			tc.connect("192.168.168.254", 23);
			InputStream is = tc.getInputStream();
			PrintStream ps = new PrintStream(tc.getOutputStream());
			readUntil(is, "Login:");
			write(ps, "nbg");
			Log.e("reboot", "input username");
			readUntil(is, "Password:");
			write(ps, "dugudao3721");
			Log.e("reboot", "input password");
			readUntil(is, "WAP>");
			write(ps, "shell");
			readUntil(is, "#");
			write(ps, "reboot");
			Log.e("reboot", "reboot complete");

			Editor editor = preferences.edit();
			editor.putLong("last_reboot_time", System.currentTimeMillis());
			editor.putBoolean("network_test", false);
			editor.commit();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String readUntil(InputStream is, String pattern) {
		try {
			char lastChar = pattern.charAt(pattern.length() - 1);
			StringBuffer sb = new StringBuffer();
			char ch = (char) is.read();
			while (true) {
				sb.append(ch);
				if (ch == lastChar) {
					if (sb.toString().endsWith(pattern)) {
						return sb.toString();
					}
				}
				ch = (char) is.read();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void write(PrintStream ps, String value) {
		try {
			ps.println(value);
			ps.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
